import LinkedList from "./linked_list";
import Node from "./node";
import defaultEquals from "./util";

export default class CircularLinkedList <T> extends LinkedList <T> {
    constructor(equalsFn=defaultEquals){
        super(equalsFn)
    }
    // 哪些方法要改
    push(element: T): void {
        let node=new Node(element)
        if(this.size()===0){
            this.head=node
            node.next=this.head
            return ;
        }
        let previous=this.getElementAt(this.size())
        node.next=previous.next
        previous.next=node
    }
    insert(element: T, index: number): boolean {
        if(index>0&&index<=this.count){
            const node=new Node(element);
            if(index===0){
                let current=this.head;
                if(this.head==null){
                    this.head=node;
                    node.next=this.head
                }
                else{
                    // 链表头部不为空，node的next指向当前head
                    node.next=current
                    current=this.getElementAt(this.size()-1)
                    this.head=node
                    current.next=this.head
                }
            }
            else{
                const previous=this.getElementAt(index-1)
                node.next=previous.next
                previous.next=node
            }
            this.count++
            return true
        }
        return false
    }
    removeAt(index: number): true | undefined {
        if(index>=0&&index<this.count){
            let previous=this.getElementAt(this.size());
            let current=this.head
            if(index===0){
                if(this.size()==1){
                    this.head=undefined
                }
                else{
                    const removed=this.head
                    this.head=this.head.next
                    previous.next=this.head
                    current=removed
                }
            }
            else{
                previous=this.getElementAt(index-1)
                current=previous.next
                previous.next=current.next
            }
            this.count--
            return current.element
        }
        return undefined
    }
}
